<template>
  <div class="tree-editor-container">
    <div class="filter-bar">
      <el-select
        v-model="selectedBranchId"
        placeholder="选择分支"
        style="width: 200px; margin-right: 10px;"
        @change="onBranchChange"
        clearable
      >
        <el-option label="全部分支" :value="null" />
        <el-option
          v-for="branch in branches"
          :key="branch.id"
          :label="branch.name"
          :value="branch.id"
        />
      </el-select>

      <el-input
        v-model="searchName"
        placeholder="输入姓名搜索成员"
        style="width: 300px; margin-right: 10px;"
        @keyup.enter.native="onSearch"
        clearable
      />
      <el-button @click="onSearch" type="primary" size="small" :loading="searching">
        搜索
      </el-button>
      <el-button @click="clearSearch" size="small" v-if="searchName">
        清空
      </el-button>
    </div>

    <div class="tree-container">
      <div v-if="treeData.length === 0" class="no-data">
        <p>暂无数据</p>
        <el-button @click="loadRoot" type="primary" size="small">重新加载</el-button>
      </div>
      <div v-else>
        <p>找到 {{ treeData.length }} 个根节点</p>
        <el-tree
          ref="tree"
          :data="treeData"
          :props="treeProps"
          :load="loadChildren"
          lazy
          :highlight-current="true"
          :default-expanded-keys="expandedKeys"
          :default-checked-keys="selectedKeys"
          node-key="id"
          @node-click="handleNodeClick"
          :expand-on-click-node="false"
          draggable
          @node-drag-start="handleDragStart"
          @node-drag-enter="handleDragEnter"
          @node-drag-leave="handleDragLeave"
          @node-drag-end="handleDragEnd"
          @node-drop="handleDrop"
          :allow-drop="allowDrop"
          :allow-drag="allowDrag"
        >
        </el-tree>
      </div>
    </div>
  </div>
</template>

<script>
import { getEnhancedTreeChildren, searchEnhancedTreeByName, updateMemberParent } from '@/api/member'
import { getBranchList } from '@/api/branch'
import request from '@/api/request'

export default {
  name: 'TreeEditor',
  data() {
    return {
      treeData: [],
      treeProps: {
        label: 'name',
        children: 'children',
        isLeaf: 'isLeaf'
      },
      searchName: '',
      expandedKeys: [],
      selectedKeys: [],
      selectedId: null,
      searching: false,
      // 新增：分支相关数据
      branches: [],
      selectedBranchId: null
    }
  },
  created() {
    this.loadBranches()
    this.loadRoot()
  },
  methods: {
    // 新增：加载分支列表
    async loadBranches() {
      try {
        const res = await getBranchList()
        this.branches = res.records || []
      } catch (error) {
        console.error('加载分支列表失败:', error)
      }
    },

    // 新增：分支切换处理
    onBranchChange() {
      this.clearSearch()
      this.loadRoot()
    },

    async loadRoot() {
      try {
        // 当选择"全部分支"时，selectedBranchId 为 null，应该不传递分支参数
        const branchId = this.selectedBranchId === null ? undefined : this.selectedBranchId
        const res = await getEnhancedTreeChildren(null, branchId)
        console.log('Root data:', res)
        // 由于响应拦截器已经提取了 data，所以 res 就是数据本身
        const rootData = (res || []).map(item => ({
          ...item,
          isLeaf: item.isLeaf || false
        }))
        this.treeData = rootData
        console.log('Tree data set:', this.treeData)
        console.log('Tree data length:', this.treeData.length)
      } catch (error) {
        this.$message.error('加载根节点失败')
        console.error(error)
      }
    },

    async loadChildren(node, resolve) {
      try {
        console.log('Loading children for node:', node.data.id)
        // 当选择"全部分支"时，selectedBranchId 为 null，应该不传递分支参数
        const branchId = this.selectedBranchId === null ? undefined : this.selectedBranchId
        const res = await getEnhancedTreeChildren(node.data.id, branchId)
        console.log('Children data:', res)
        // 确保每个节点都有正确的 isLeaf 属性
        const children = (res || []).map(item => ({
          ...item,
          isLeaf: item.isLeaf || false
        }))
        console.log('Processed children:', children)
        resolve(children)
      } catch (error) {
        this.$message.error('加载子节点失败')
        console.error(error)
        resolve([])
      }
    },

    handleNodeClick(data, node) {
      this.selectedId = data.id
      console.log('选中节点:', data)
    },

    async onSearch() {
      if (!this.searchName.trim()) {
        this.$message.warning('请输入搜索姓名')
        return
      }

      this.searching = true
      try {
        const res = await searchEnhancedTreeByName(this.searchName.trim())
        if (res && res.length > 0) {
          // 展开所有父链
          const ids = res.map(n => n.id)
          this.expandedKeys = ids
          this.selectedKeys = [res[0].id]
          this.selectedId = res[0].id

          // 定位到选中节点
          this.$nextTick(() => {
            this.$refs.tree.setCurrentKey(this.selectedId)
            // 滚动到选中节点
            const node = this.$refs.tree.getNode(this.selectedId)
            if (node) {
              node.expand()
            }
          })

          this.$message.success(`找到 ${res.length} 个相关成员`)
        } else {
          this.$message.warning('未找到相关成员')
        }
      } catch (error) {
        this.$message.error('搜索失败')
        console.error(error)
      } finally {
        this.searching = false
      }
    },

    clearSearch() {
      this.searchName = ''
      this.expandedKeys = []
      this.selectedKeys = []
      this.selectedId = null
    },

    // 新增：拖拽相关方法
    handleDragStart(node, ev) {
      console.log('开始拖拽:', node.data)
    },

    handleDragEnter(draggingNode, dropNode, ev) {
      console.log('拖拽进入:', dropNode.data)
    },

    handleDragLeave(draggingNode, dropNode, ev) {
      console.log('拖拽离开:', dropNode.data)
    },

    handleDragEnd(draggingNode, dropNode, dropType, ev) {
      console.log('拖拽结束:', dropType)
    },

    handleDrop(draggingNode, dropNode, dropType, ev) {
      console.log('节点放置:', {
        draggingNode: draggingNode.data,
        dropNode: dropNode.data,
        dropType: dropType
      })

      // 调用后端API来更新父子关系
      this.updateMemberParent(draggingNode.data.id, dropNode.data.id)
    },

    // 新增：调用后端API更新父节点关系
    async updateMemberParent(memberId, newParentId) {
      try {
        const response = await updateMemberParent(memberId, newParentId)
        console.log('updateMemberParent', response)
        if (response && response.code === 0) {
          this.$message.success('拖拽操作完成')
          // 重新加载数据
          this.loadRoot()
        } else {
          this.$message.error((response && response.msg) || '拖拽操作失败')
        }
      } catch (error) {
        console.error('更新父节点失败:', error)
        this.$message.error('拖拽操作失败')
      }
    },

    allowDrop(draggingNode, dropNode, type) {
      // 不允许拖拽到自身
      if (draggingNode.data.id === dropNode.data.id) {
        return false
      }

      // 不允许拖拽到子节点
      const isChild = this.isChildNode(draggingNode.data.id, dropNode.data.id)
      if (isChild) {
        return false
      }

      return true
    },

    allowDrag(node) {
      // 允许拖拽所有节点
      return true
    },

    // 检查是否为子节点
    isChildNode(draggingNodeId, dropNodeId) {
      const node = this.$refs.tree.getNode(dropNodeId)
      if (!node) return false

      let current = node.parent
      while (current && current.data) {
        if (current.data.id === draggingNodeId) {
          return true
        }
        current = current.parent
      }
      return false
    },

    getGenderText(gender) {
      return gender === 'M' ? '男' : gender === 'F' ? '女' : '未知'
    },

    getChildOrderText(order, gender) {
      if (!order || order === 0) return ''
      if (order === 1) return gender === 'M' ? '长子' : '长女'
      if (order === 2) return gender === 'M' ? '次子' : '次女'
      if (order === 3) return gender === 'M' ? '三子' : '三女'
      return `第${order}子`
    },

    getImageUrl(photoPath) {
      if (!photoPath) return ''
      if (photoPath.startsWith('http')) {
        return photoPath
      }
      return photoPath
    },

    renderContent(h, { node, data, store }) {
      return h('div', {
        class: {
          'tree-node': true,
          'selected': data.id === this.selectedId
        }
      }, [
        h('div', {
          class: 'node-content'
        }, [
          data.photo ? h('div', {
            class: 'node-avatar'
          }, [
            h('img', {
              attrs: {
                src: this.getImageUrl(data.photo),
                alt: data.name
              }
            })
          ]) : null,
          h('div', {
            class: 'node-info'
          }, [
            h('span', {
              class: 'node-name'
            }, data.name),
            h('span', {
              class: 'node-details'
            }, [
              `${this.getGenderText(data.gender)} · 第${data.generation}代`,
              data.childOrder && data.childOrder > 0 ? h('span', {
                class: 'child-order'
              }, ` (${this.getChildOrderText(data.childOrder, data.gender)})`) : null,
              h('el-tag', {
                props: {
                  type: data.status === '在世' ? 'success' : 'info',
                  size: 'mini'
                },
                style: {
                  marginLeft: '8px'
                }
              }, data.status)
            ])
          ])
        ])
      ])
    }
  }
}
</script>

<style scoped>
.tree-editor-container {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;
}

.search-bar {
  margin-bottom: 20px;
  padding: 16px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.tree-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  padding: 16px;
  max-height: 600px;
  overflow-y: auto;
}

.no-data {
  text-align: center;
  padding: 40px;
  color: #909399;
}

.no-data p {
  margin-bottom: 16px;
  font-size: 14px;
}

.tree-node {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-radius: 4px;
  transition: all 0.2s;
  cursor: pointer;
  width: 100%;
}

.tree-node:hover {
  background: #f0f7ff;
}

.tree-node.selected {
  background: #e6f7ff;
  border-left: 3px solid #409eff;
}

.node-content {
  display: flex;
  align-items: center;
  width: 100%;
}

.node-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 12px;
  flex-shrink: 0;
}

.node-avatar img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.node-info {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.node-name {
  font-weight: 600;
  color: #303133;
  font-size: 14px;
  line-height: 1.4;
}

.node-details {
  font-size: 12px;
  color: #909399;
  margin-top: 2px;
  line-height: 1.4;
  display: flex;
  align-items: center;
}

.child-order {
  color: #409eff;
  font-weight: 500;
}

/* Element UI Tree 样式优化 */
::v-deep .el-tree {
  background: transparent;
}

::v-deep .el-tree-node__content {
  height: auto;
  padding: 0;
}

::v-deep .el-tree-node__expand-icon {
  color: #909399;
}

::v-deep .el-tree-node__label {
  flex: 1;
  padding: 0;
}
</style>
